﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using PersonalHealth.Data.Model;
using PersonalHealth.Data.Service;
using PersonalHealth.Data.IService;
using System.IO;
using System.Diagnostics;
using System.Windows.Interop;
using HealthManagement.Common;
using UI.Comm.Controls;

namespace HealthManagement.Views
{
    /// <summary>
    /// HealthReport.xaml 的交互逻辑
    /// </summary>
    public partial class HealthReport : PMWindow
    {
        MeasureUser measureUser;
        private string htmlStr;
        HealthReportPage wbo;

        public HealthReport( MeasureUser measureUser)
        {
            InitializeComponent();
            this.Unloaded += new RoutedEventHandler(HealthReport_Unloaded);
            this.measureUser = measureUser;
            timeStart.SelectedValue = DateTime.Now.AddDays(-7);
            timeEnd.SelectedValue = DateTime.Now;
            string[] typeList = { "所有类型", "血压", "血糖", "血氧", "体温" };
            TypeCBox.ItemsSource = typeList;
            TypeCBox.SelectedIndex = 0;
        }

        void HealthReport_Unloaded(object sender, RoutedEventArgs e)
        {
            if (wbo != null)
                wbo.Close();
        }

        public HealthReport(string content)
        {
            InitializeComponent();
            this.Unloaded += new RoutedEventHandler(HealthReport_Unloaded);
            bottomBorder.Visibility = topPanel.Visibility = Visibility.Collapsed;
            wbo = new HealthReportPage(resultStepGrid);
            WebBrowser wb = wbo.WebBrowser;
            Stream stream = new MemoryStream(Encoding.Default.GetBytes(content));
            wb.NavigateToStream(stream);
        }

      

        private void Send_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<p><span class=\"auto-style2\">医师建议</span> </p>");
            sb.Append("<div style=\"border-style: solid; border-width: 1px; border-color: #2380FF; width: 100%;\">");
            sb.Append("<p class=\"p_B0B4BECC\"><span class=\"s_79B9C72D\">@obj_comment</span></p>");
            sb.Append("</div>");
            sb = sb.Replace("@obj_comment" ,string.IsNullOrEmpty(tbComment.Text) ? "医师未填写医嘱！" : tbComment.Text);

            int idx = htmlStr.LastIndexOf("</body>");
            htmlStr = htmlStr.Insert(idx, sb.ToString());
            
            string text = htmlStr.ToString();
            IDoctorService ser = new DoctorService();
            string title = string.Format("{0}_{1}_健康报告", DateTime.Now.ToShortDateString(), TypeCBox.SelectedValue.ToString());
            ser.SendHealthReport(measureUser.Id, title, text);
            this.Close();
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Next_Click(object sender, RoutedEventArgs e)
        {
            resultStepGrid.Visibility = Visibility.Visible;
            //Next.Visibility = Visibility.Collapsed;
            Save.Visibility = Visibility.Visible;
            Cancel.Visibility = Visibility.Visible;
            tbComment.Visibility = Visibility.Visible;

            Save.IsEnabled = true;

            DateTime start = timeStart.SelectedValue.Value;
            DateTime end = timeEnd.SelectedValue.Value;
            generateReport(start, end);
        }

        private void generateReport(DateTime start, DateTime end)
        {
            string selectedType = TypeCBox.SelectedValue.ToString();
            string path = string.Format("{0}/Template/HealthReportTemplate.html", System.IO.Directory.GetCurrentDirectory());
            string htmlTemplate = File.ReadAllText(path);
            htmlTemplate = htmlTemplate.Replace("@obj_logo", string.Format("{0}/Template/logo.png", System.IO.Directory.GetCurrentDirectory()));
            htmlTemplate = htmlTemplate.Replace("@obj_currTime", DateTime.Now.ToShortDateString());
            htmlTemplate = htmlTemplate.Replace("@obj_name", measureUser.UserName);
            if (measureUser.Birthday != null)
                htmlTemplate = htmlTemplate.Replace("@obj_age", (DateTime.Now.Year - measureUser.Birthday.Value.Year).ToString());
            else
                htmlTemplate = htmlTemplate.Replace("@obj_age", "");
            if (measureUser.BloodType != null)
                htmlTemplate = htmlTemplate.Replace("@obj_bloodType",measureUser.BloodType.Name);
            else
                htmlTemplate = htmlTemplate.Replace("@obj_bloodType", "");
            if (measureUser.Sex != null)
                htmlTemplate = htmlTemplate.Replace("@obj_sex", measureUser.Sex.Name);
            else
                htmlTemplate = htmlTemplate.Replace("@obj_sex", "");
            if (measureUser.Weight != null)
                htmlTemplate = htmlTemplate.Replace("@obj_weight", measureUser.Weight.Value.ToString()+"公斤");
            else
                htmlTemplate = htmlTemplate.Replace("@obj_weight", "");
            if (measureUser.Height != null)
                htmlTemplate = htmlTemplate.Replace("@obj_height", measureUser.Height.Value.ToString()+"cm");
            else
                htmlTemplate = htmlTemplate.Replace("@obj_height", "");

            StringBuilder measureData = null;         

            switch (selectedType)
            {
                case "所有类型":
                    measureData = new StringBuilder();
                    IMeasure_BPService bpser1 = new Measure_BPService();
                    var bpOrderby1 = new Func<Measure_BP, DateTime>[] { new Func<Measure_BP, DateTime>(c => c.MeasureTime) };
                    var bplist1 = bpser1.Find(c => c.UserId == measureUser.Id && c.MeasureTime >= start && c.MeasureTime <= end,
                                    bpOrderby1, new bool[] { false }, 1, 100);
                    measureData.Append(generateBP(bplist1, htmlTemplate));

                    IMeasure_BGService bgser1 = new Measure_BGService();
                    var bgOrderby1 = new Func<Measure_BG, DateTime>[] { new Func<Measure_BG, DateTime>(c => c.MeasureTime) };
                    var bglist1 = bgser1.Find(c => c.UserId == measureUser.Id && c.MeasureTime >= start && c.MeasureTime <= end,
                                    bgOrderby1, new bool[] { false }, 1, 100);
                    measureData.Append(generateBG(bglist1, htmlTemplate));

                    IMeasure_BOService boser1 = new Measure_BOService();
                    var boOrderby1 = new Func<Measure_BO, DateTime>[] { new Func<Measure_BO, DateTime>(c => c.MeasureTime) };
                    var bolist1 = boser1.Find(c => c.UserId == measureUser.Id && c.MeasureTime >= start && c.MeasureTime <= end,
                                    boOrderby1, new bool[] { false }, 1, 100);
                    measureData.Append(generateBO(bolist1, htmlTemplate));

                    IMeasure_TempService tempser1 = new Measure_TempService();
                    var tempOrderby1 = new Func<Measure_Temp, DateTime>[] { new Func<Measure_Temp, DateTime>(c => c.MeasureTime) };
                    var templist1 = tempser1.Find(c => c.UserId == measureUser.Id && c.MeasureTime >= start && c.MeasureTime <= end,
                                    tempOrderby1, new bool[] { false }, 1, 100);
                    measureData.Append(generateTemp(templist1, htmlTemplate));
                    break;
                case "血压":
                    IMeasure_BPService bpser = new Measure_BPService();
                    var bpOrderby = new Func<Measure_BP, DateTime>[] { new Func<Measure_BP, DateTime>(c => c.MeasureTime) };
                    var bplist = bpser.Find(c => c.UserId == measureUser.Id && c.MeasureTime >= start && c.MeasureTime <= end,
                                    bpOrderby, new bool[] { false }, 1, 100);
                    measureData = generateBP(bplist, htmlTemplate);
                    break;
                case "血糖":
                    IMeasure_BGService bgser = new Measure_BGService();
                    var bgOrderby = new Func<Measure_BG, DateTime>[] { new Func<Measure_BG, DateTime>(c => c.MeasureTime) };
                    var bglist = bgser.Find(c => c.UserId == measureUser.Id && c.MeasureTime >= start && c.MeasureTime <= end,
                                    bgOrderby, new bool[] { false }, 1, 100);
                    measureData = generateBG(bglist, htmlTemplate);
                    break;
                case "血氧":
                    IMeasure_BOService boser = new Measure_BOService();
                    var boOrderby = new Func<Measure_BO, DateTime>[] { new Func<Measure_BO, DateTime>(c => c.MeasureTime) };
                    var bolist = boser.Find(c => c.UserId == measureUser.Id && c.MeasureTime >= start && c.MeasureTime <= end,
                                    boOrderby, new bool[] { false }, 1, 100);
                    measureData = generateBO(bolist, htmlTemplate);
                    break;
                case "体温":
                    IMeasure_TempService tempser = new Measure_TempService();
                    var tempOrderby = new Func<Measure_Temp, DateTime>[] { new Func<Measure_Temp, DateTime>(c => c.MeasureTime) };
                    var templist = tempser.Find(c => c.UserId == measureUser.Id && c.MeasureTime >= start && c.MeasureTime <= end,
                                    tempOrderby, new bool[] { false }, 1, 100);
                    measureData = generateTemp(templist, htmlTemplate);
                    break;
                case "心电":
                    IMeasure_ECGService ecgser = new Measure_ECGService();
                    break;
                default:
                    break;
            }
            if (measureData != null)
            {
                htmlStr = htmlTemplate.Replace("@obj_measureData", measureData.ToString());
                wbo = new HealthReportPage(resultStepGrid);
                WebBrowser wb = wbo.WebBrowser;
                Stream stream = new MemoryStream(Encoding.Default.GetBytes(htmlStr));
                wb.NavigateToStream(stream);
            }
        }
       

        private StringBuilder generateBP(IList<Measure_BP> list,string htmlTemplate)
        {
            DateTime start = timeStart.SelectedValue.Value;
            DateTime end = timeEnd.SelectedValue.Value;
            string timespan = string.Format("（{0} - {1}）", start.ToShortDateString(), end.ToShortDateString()); ;
            IUserService service = new UserService();
            var thresholds = service.GetThreshold("BP", measureUser.Id);
            Dictionary<string, Threshold> hash = new Dictionary<string, Threshold>();
            foreach (var i in thresholds)
            {
                hash.Add(i.MeasureSubType.Code, i);
            }

            StringBuilder sb1 = new StringBuilder();
            sb1.Append("<div style=\"border-style: solid; border-width: 1px; border-color: #2380FF; width: 100%;\">");
            sb1.Append("<tr><td class=\"auto-style3\" colspan=\"4\">@type</td></tr>");
            sb1.Append("<table style=\"width: 100%;\">");
            sb1.Append("<tr style=\"height: 50px\">");
			sb1.Append("<td style=\"width: 150px; color: gray\">测量结果 </td>");
			sb1.Append("<td style=\"width: 150px; color: gray\">Normal </td>");
			sb1.Append("<td style=\"width: 150px; color: gray\">测量时间</td>");
			sb1.Append("<td style=\"color: gray\">Treated by</td>");
		    sb1.Append("</tr>");
            
            StringBuilder sb2 = new StringBuilder(sb1.ToString());
            StringBuilder sb3 = new StringBuilder(sb1.ToString());

            sb1 = sb1.Replace("@type", "收缩压(mmHg)"); //SBP
            sb2 = sb2.Replace("@type", "舒张压(mmHg)"); //DBP
            sb3 = sb3.Replace("@type", "心率(bpm)"); //HR_Value

            foreach (var i in list)
            {
                sb1.Append("<tr>");
                sb1.Append(string.Format("<td>{0}</td>", i.SBP));
                sb1.Append(string.Format("<td>{0}</td>", i.SBP >= hash["SBP"].Min && i.SBP <= hash["SBP"].Max ? "正常" : "异常"));
                sb1.Append(string.Format("<td>{0}</td>", i.MeasureTime));
                sb1.Append(string.Format("<td>{0}</td>", AppData.User == null ? "-" : AppData.User.UserName));
                sb1.Append("</tr>");

                sb2.Append("<tr>");
                sb2.Append(string.Format("<td>{0}</td>", i.DBP));
                sb2.Append(string.Format("<td>{0}</td>", i.DBP >= hash["DBP"].Min && i.DBP <= hash["DBP"].Max ? "正常" : "异常"));
                sb2.Append(string.Format("<td>{0}</td>", i.MeasureTime));
                sb2.Append(string.Format("<td>{0}</td>", AppData.User == null ? "-" : AppData.User.UserName));
                sb2.Append("</tr>");

                sb3.Append("<tr>");
                sb3.Append(string.Format("<td>{0}</td>", i.HR_Value));
                sb3.Append(string.Format("<td>{0}</td>", i.HR_Value >= hash["HR_Value"].Min && i.HR_Value <= hash["HR_Value"].Max ? "正常" : "异常"));
                sb3.Append(string.Format("<td>{0}</td>", i.MeasureTime));
                sb3.Append(string.Format("<td>{0}</td>", AppData.User == null ? "-" : AppData.User.UserName));
                sb3.Append("</tr>");
            }

            sb1.Append("</table></div>");
            sb2.Append("</table></div>");
            sb3.Append("</table></div>");

            StringBuilder measureData = new StringBuilder();
            measureData.Append(string.Format("<p><span class=\"auto-style2\">测量结果--{0}</span> <span style=\"color: gray\">{1}</span></p>", "血压", timespan));
            measureData.Append(sb1);
            measureData.Append("<p style=\"height: 2px\">&nbsp;</p>");
            measureData.Append(sb2);
            measureData.Append("<p style=\"height: 2px\">&nbsp;</p>");
            measureData.Append(sb3);

            return measureData;
            
        }

        private StringBuilder generateBG(IList<Measure_BG> list, string htmlTemplate)
        {
            DateTime start = timeStart.SelectedValue.Value;
            DateTime end = timeEnd.SelectedValue.Value;
            string timespan = string.Format("（{0} - {1}）", start.ToShortDateString(), end.ToShortDateString());
            IUserService service = new UserService();
            var thresholds = service.GetThreshold("BG", measureUser.Id);
            Dictionary<string, Threshold> hash = new Dictionary<string, Threshold>();
            foreach (var i in thresholds)
            {
                hash.Add(i.MeasureSubType.Code, i);
            }

            StringBuilder sb1 = new StringBuilder();
            sb1.Append("<div style=\"border-style: solid; border-width: 1px; border-color: #2380FF; width: 100%;\">");
            sb1.Append("<tr><td class=\"auto-style3\" colspan=\"4\">@type</td></tr>");
            sb1.Append("<table style=\"width: 100%;\">");
            sb1.Append("<tr style=\"height: 50px\">");
            sb1.Append("<td style=\"width: 150px; color: gray\">测量结果 </td>");
            sb1.Append("<td style=\"width: 150px; color: gray\">Normal </td>");
            sb1.Append("<td style=\"width: 150px; color: gray\">测量时间</td>");
            sb1.Append("<td style=\"color: gray\">Treated by</td>");
            sb1.Append("</tr>");


            sb1 = sb1.Replace("@type", "血糖(mmol/L)"); 

            foreach (var i in list)
            {
                sb1.Append("<tr>");
                sb1.Append(string.Format("<td>{0}</td>", i.BloodGlucose));
                sb1.Append(string.Format("<td>{0}</td>", i.BloodGlucose >= hash["BloodGlucose"].Min && i.BloodGlucose <= hash["BloodGlucose"].Max ? "正常" : "异常"));
                sb1.Append(string.Format("<td>{0}</td>", i.MeasureTime));
                sb1.Append(string.Format("<td>{0}</td>", AppData.User == null ? "-" : AppData.User.UserName));
                sb1.Append("</tr>");

            }

            sb1.Append("</table></div>");

            StringBuilder measureData = new StringBuilder();
            measureData.Append(string.Format("<p><span class=\"auto-style2\">测量结果--{0}</span> <span style=\"color: gray\">{1}</span></p>", "血糖", timespan));
            measureData.Append(sb1);

            return measureData;

        }

        private StringBuilder generateBO(IList<Measure_BO> list, string htmlTemplate)
        {
            DateTime start = timeStart.SelectedValue.Value;
            DateTime end = timeEnd.SelectedValue.Value;
            string timespan= string.Format("（{0} - {1}）", start.ToShortDateString(), end.ToShortDateString());
            IUserService service = new UserService();
            var thresholds = service.GetThreshold("BO", measureUser.Id);
            Dictionary<string, Threshold> hash = new Dictionary<string, Threshold>();
            foreach (var i in thresholds)
            {
                hash.Add(i.MeasureSubType.Code, i);
            }

            StringBuilder sb1 = new StringBuilder();
            sb1.Append("<div style=\"border-style: solid; border-width: 1px; border-color: #2380FF; width: 100%;\">");
            sb1.Append("<tr><td class=\"auto-style3\" colspan=\"4\">@type</td></tr>");
            sb1.Append("<table style=\"width: 100%;\">");
            sb1.Append("<tr style=\"height: 50px\">");
            sb1.Append("<td style=\"width: 150px; color: gray\">测量结果 </td>");
            sb1.Append("<td style=\"width: 150px; color: gray\">Normal </td>");
            sb1.Append("<td style=\"width: 150px; color: gray\">测量时间</td>");
            sb1.Append("<td style=\"color: gray\">Treated by</td>");
            sb1.Append("</tr>");

            StringBuilder sb2 = new StringBuilder(sb1.ToString());

            sb1 = sb1.Replace("@type", "血氧饱和度(%)");
            sb2 = sb2.Replace("@type", "脉率(bpm)"); 

            foreach (var i in list)
            {
                sb1.Append("<tr>");
                sb1.Append(string.Format("<td>{0}</td>", i.SpO2));
                sb1.Append(string.Format("<td>{0}</td>", i.SpO2 >= hash["SpO2"].Min && i.SpO2 <= hash["SpO2"].Max ? "正常" : "异常"));
                sb1.Append(string.Format("<td>{0}</td>", i.MeasureTime));
                sb1.Append(string.Format("<td>{0}</td>", AppData.User == null ? "-" : AppData.User.UserName));
                sb1.Append("</tr>");

                sb2.Append("<tr>");
                sb2.Append(string.Format("<td>{0}</td>", i.Pulse));
                sb2.Append(string.Format("<td>{0}</td>", i.Pulse >= hash["Pulse"].Min && i.Pulse <= hash["Pulse"].Max ? "正常" : "异常"));
                sb2.Append(string.Format("<td>{0}</td>", i.MeasureTime));
                sb2.Append(string.Format("<td>{0}</td>", AppData.User == null ? "-" : AppData.User.UserName));
                sb2.Append("</tr>");

            }

            sb1.Append("</table></div>");
            sb2.Append("</table></div>");

            StringBuilder measureData = new StringBuilder();
            measureData.Append(string.Format("<p><span class=\"auto-style2\">测量结果--{0}</span> <span style=\"color: gray\">{1}</span></p>", "血氧", timespan));
            measureData.Append(sb1);
            measureData.Append("<p style=\"height: 2px\">&nbsp;</p>");
            measureData.Append(sb2);

            return measureData;

        }

        private StringBuilder generateTemp(IList<Measure_Temp> list, string htmlTemplate)
        {
            DateTime start = timeStart.SelectedValue.Value;
            DateTime end = timeEnd.SelectedValue.Value;
            string timespan = string.Format("（{0} - {1}）", start.ToShortDateString(), end.ToShortDateString());
            IUserService service = new UserService();
            var thresholds = service.GetThreshold("Temp", measureUser.Id);
            Dictionary<string, Threshold> hash = new Dictionary<string, Threshold>();
            foreach (var i in thresholds)
            {
                hash.Add(i.MeasureSubType.Code, i);
            }

            StringBuilder sb1 = new StringBuilder();
            sb1.Append("<div style=\"border-style: solid; border-width: 1px; border-color: #2380FF; width: 100%;\">");
            sb1.Append("<tr><td class=\"auto-style3\" colspan=\"4\">@type</td></tr>");
            sb1.Append("<table style=\"width: 100%;\">");
            sb1.Append("<tr style=\"height: 50px\">");
            sb1.Append("<td style=\"width: 150px; color: gray\">测量结果 </td>");
            sb1.Append("<td style=\"width: 150px; color: gray\">Normal </td>");
            sb1.Append("<td style=\"width: 150px; color: gray\">测量时间</td>");
            sb1.Append("<td style=\"color: gray\">Treated by</td>");
            sb1.Append("</tr>");


            sb1 = sb1.Replace("@type", "体温(℃)");

            foreach (var i in list)
            {
                sb1.Append("<tr>");
                sb1.Append(string.Format("<td>{0}</td>", i.Temp));
                sb1.Append(string.Format("<td>{0}</td>", i.Temp >= hash["Temp"].Min && i.Temp <= hash["Temp"].Max ? "正常" : "异常"));
                sb1.Append(string.Format("<td>{0}</td>", i.MeasureTime));
                sb1.Append(string.Format("<td>{0}</td>", AppData.User == null ? "-" : AppData.User.UserName));
                sb1.Append("</tr>");

            }

            sb1.Append("</table></div>");

            StringBuilder measureData = new StringBuilder();
            measureData.Append(string.Format("<p><span class=\"auto-style2\">测量结果--{0}</span> <span style=\"color: gray\">{1}</span></p>", "体温", timespan));
            measureData.Append(sb1);

            return measureData;

        }
    }
}
